import React, { Component , Fragment } from 'react' ;
import { Tree , MessageBox , Input, Button , Table , Form ,Tag , Select,Message,Pagination} from "element-react" ;
import PubSub from "pubsub-js";
import './index.css';

const Devicepageurl = "/device/devicemanageinfo/"

class Deviceinfo extends Component {
  state = {
    dialogVisible: false,
    form: {
      label: '',
      type: ''
    },
    data: [],
    options: {
      children: 'children',
      label: 'label'
    },
  }

  netcontorll = new AbortController()

  componentDidMount(){
   fetch("/device/devicebaiseinfo/devicelist")
    .then(data => data.json())
    .then(result=>{
      this.setState({data:result.data});
    })
  }

  componentWillUnmount(){
    //防止组件加载网络还未出结果组件就被卸载了导致的异常
    this.netcontorll.abort()
  }

  append(store, data ) {
  }
  
  addDevice = async (data)=>{

   }



  remove = (nodeModel ,store, data )=> {
  } 

  getTopId(node , tree){
    if(node.data.level===0) {
      return node.data.id;
    }
    return this.getTopId(tree.root.store.getNode(node.data.parent) , tree) ;
  }

  removeDevice = (ids , store , data )=>{
  }
  nodeClicked = (data, node , tree)=>{
   let topid = this.getTopId(tree.root.store.getNode(data.id) , tree)
    console.log(topid) ;
      if(data.children.length===0) {
        data.topid = topid ;
        PubSub.publish("device-info" , data);
      }
  }
  render() {
    
    const { data, options } = this.state
    return (
      <div>
        <Input placeholder="输入关键字进行过滤" onChange={text=> this.tree.filter(text)} />
        <Tree
          ref={e=> this.tree = e}
          data={data}
          options={options}
          nodeKey="id"
          expandOnClickNode={true}
          highlightCurrent={true}
          onNodeClicked={(data ,node)=>{this.nodeClicked(data, node, this.tree)}}
          filterNodeMethod={(value, data)=>{
            if (!value) return true;
            return data.label.indexOf(value) !== -1;
          }}
        />
      </div>
    )
  }
}

export default class DeviceManage extends Component {

  componentDidMount(){
    this.pubsubid = PubSub.subscribe("device-info",(msg , value)=>{
      fetch(Devicepageurl+"list" , {
        method:"POST",
        headers:{
          "Content-Type": "application/json",
        },
        body:JSON.stringify({type:value.id})
      }).then(data=>data.json())
      .then(result =>{
        console.log(result) ;
        result.page.list.map((e)=>{
          e.lable = value.label
          return e 
        })
        this.setState({data:result.page.list,currentnode:value ,top:value.topid, page :{
          total: result.page.totalPage,
          pageSize:  result.page.pageSize,
          currentPage: result.page.currPage,
        }})
      })  
    });
  }

  componentWillUnmount(){
    PubSub.unsubscribe(this.pubsubid);
  }

  statusmap = {
    0 : {tag:"success" ,
         name:"在库"} , //在库
    1 : {tag:"danger",
          name :"维修中"} ,  // 维修中
    2 : { tag:"primary" ,
          name : "借出" } , //借出
    3 : {tag:"gray" ,
          name:"不可用"}, //不可用
    5 : {tag : "danger",
          name : "未入库"
    }
  }

  state = {
    columns: [
      {
        label: "设备编号",
        prop: "id",
        width: 200,
        fixed: 'left',
        align: 'center'
      },
      {
        label: "标签",
        prop: "lable",
        width: 160,
        align: 'center'
      },
      {
        label: "位置",
        prop: "location",
        align:"center",
        width: 400
      },
      {
        label: "状态",
        prop: "status",
        align: 'center',
        width: 100,
        render: (row, column, index)=>{
          return (
            <Tag
            type={this.statusmap[row.status].tag}
            >{this.statusmap[row.status].name}</Tag>
          )
        },
      },
      {
        label: "周期",
        prop: "period",
        width: 120,
        align: 'center'
      },
      {
        label: "操作",
        width: 240,
        fixed: 'right',
        render: (row, column, index)=>{
          return (
            <span style={{display:"flex"}}>
              <Button plain={true} type="info" disabled={row.status===0 ? false : true} size="small" onClick={this.alterRow.bind(this, index)}>修改</Button>
              <Button type="danger" size="small" onClick={this.deleteRow.bind(this, index)}>移除</Button>
            </span>
            )

        },
        align: 'center'
      }
    ],
    data: [] ,
    page:{} ,
    currentnode:{},
    from :{
      location:"",
      period:"",
      status:"",
    }
  }



  alterRow(index) {
    const { data } = this.state;
    MessageBox.msgbox({
      title: '操作',
      message: (
        <div>
          <Form>
          <Form.Item label={"状态"}>
            <Select onChange={(e)=>{this.state.data[index].status = e }} placeholder="状态">
                <Select.Option label="在库" value="0"></Select.Option>
                <Select.Option label="维修" value="1"></Select.Option>
                <Select.Option label="借出" value="2"></Select.Option>
                <Select.Option label="不可用" value="3"></Select.Option>
            </Select>
          </Form.Item>
          <Form.Item label='地点'>
            <Input onChange={(e)=>{this.state.data[index].location=e}}></Input>
          </Form.Item>
          </Form>
        </div>
      ),
      showCancelButton: true
    }).then(action => {
      if(action==="confirm") {
        fetch(Devicepageurl+"update" , {
          method:"POST",
          headers:{
            "Content-Type": "application/json",
          },
          body:JSON.stringify(data[index])
        }).then(data=>data.json())
        .then(result=>{
          Message({
            message: '修改成功',
            type: result.msg
          })
        })
      }
    })

  }

  deleteRow(index) {
    const { data } = this.state;
    fetch(Devicepageurl+"delete", {
      method:"POST",
      headers:{
        "Content-Type": "application/json",
      },
      body:JSON.stringify([data[index].id])
    }).then(data=>data.json())
    .then(result=>{
      data.splice(index, 1);
      this.setState({
        data: [...data]
      })
      Message({
        message: '操作成功',
        type: result.msg
      });
    })

  }

  addDevice = ()=>{
    MessageBox.msgbox({
      title: '添加设备',
      lockScroll: false ,
      customClass : "fulongwrapper" ,
      message: 
      ( <div className='fulongwrapper'>
            <Form model={this.state.form}>
              <Form.Item label="设备维护周期" > 
              <Select onChange={(e)=>{this.state.from.period = e }} placeholder="周期">
                  <Select.Option label="一个月" value="30"></Select.Option>
                  <Select.Option label="三个月" value="120"></Select.Option>
                  <Select.Option label="六个月" value="180"></Select.Option>
                  <Select.Option label="十二个月" value="360"></Select.Option>
                </Select>
              </Form.Item>
              <Form.Item label="设备仓库位置">
                <Input onChange={(e)=>{this.state.from.location = e}}></Input>
              </Form.Item>
              <Form.Item label='设备单价'>
                <Input type='number' min="1" max="1000" onChange={(e)=>{this.state.from.price = e}}></Input>
              </Form.Item>
              <Form.Item label='购买数量'>
                <Input type='number' min="1" max="100" onChange={(e)=>{this.state.from.nums = e}}></Input>
              </Form.Item>
            </Form>
        </div>
      )
      ,
      showCancelButton: true
    }).then(async action => {
      if(action==='confirm') {
         console.log(this.state.from.nums , this.state.from.price);

          let newDevice = {
            type: this.state.currentnode.id ,
            location: this.state.from.location ,
            state : 0 ,
            period:this.state.from.period,
            nums : this.state.from.nums,
            price:this.state.from.price,
            approverid:this.state.top        
          }
        fetch("/device/devicepayinfo/save",{
          method:"POST",
          headers:{
            "Content-Type": "application/json",
          },
          body:JSON.stringify(newDevice)
        }).then(data=>data.json())
        .then(result=>{
          // newDevice.id = result.id ;
          // newDevice.lable = this.state.currentnode.label ;
          // const {data} = this.state ;
          // this.setState({data:[newDevice ,...data]})
          Message({
            type:"success" ,
            message:"添加成功"
          })
        })

      }
    })
  }
  pagechange = (currentPage)=>{
    fetch(Devicepageurl+"list",{
      method:"POST",
      headers:{
        "Content-Type": "application/json",
      },
      body:JSON.stringify({type:this.state.currentnode.id , page:currentPage})
    }).then(data=>data.json())
    .then(result =>{
      result.page.list.map((e)=>{
        e.lable = this.state.currentnode.label
        return e 
      })
      this.setState({data:result.page.list , page :{
        total: result.page.totalPage,
        pageSize:  result.page.pageSize,
        currentPage: result.page.currPage,
      }})

    })
  }

  render() {
    return (
      <div className='page' >
         <div className='databar' >
          <Deviceinfo/>
         </div>
         <div className='datatable' >
           <div>
              <Button onClick={this.addDevice}>新增</Button>
           </div>
           {/* <Button>新增</Button> */}
          <Table
            style={{width: '100%'}}
            columns={this.state.columns}
            data={this.state.data}
            border={true}
            maxHeight={550}
          />
           <div className="block" style={{}}>
            <Pagination layout="prev, pager, next" 
             pageCount={this.state.page.total} 
             pageSize={this.state.page.pageSize}
             currentPage={this.state.page.currentPage}
             onCurrentChange={this.pagechange}/>
           </div>
         </div>
      </div>
    )
  }
}
